<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.png">
  <link rel="mask-icon" href="/images/avatar.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notes.maxwi.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":true,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="自己学习python 3.x的笔记，主要内容来源于A byte of python(已看完)和python官网文档Python 3.4.3 documentation(其中的Tutorial已看完)。">
<meta property="og:type" content="article">
<meta property="og:title" content="Python学习笔记">
<meta property="og:url" content="http://notes.maxwi.com/2015/05/03/Python-study-notes/index.html">
<meta property="og:site_name" content="blueyi&#39;s notes">
<meta property="og:description" content="自己学习python 3.x的笔记，主要内容来源于A byte of python(已看完)和python官网文档Python 3.4.3 documentation(其中的Tutorial已看完)。">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2015-05-03T13:33:28.000Z">
<meta property="article:modified_time" content="2015-05-03T13:33:28.000Z">
<meta property="article:author" content="blueyi">
<meta property="article:tag" content="Notes">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://notes.maxwi.com/2015/05/03/Python-study-notes/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>Python学习笔记 | blueyi's notes</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="blueyi's notes" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="blueyi's notes" type="application/rss+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">blueyi's notes</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Follow Excellence,Success will chase you!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://notes.maxwi.com/2015/05/03/Python-study-notes/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/default_avatar.jpg">
      <meta itemprop="name" content="blueyi">
      <meta itemprop="description" content="心怀善意，虛怀若谷！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="blueyi's notes">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Python学习笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2015-05-03 21:33:28" itemprop="dateCreated datePublished" datetime="2015-05-03T21:33:28+08:00">2015-05-03</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="Symbols count in article">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">Symbols count in article: </span>
              <span>18k</span>
            </span>
            <span class="post-meta-item" title="Reading time">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">Reading time &asymp;</span>
              <span>16 mins.</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>自己学习python 3.x的笔记，主要内容来源于<a target="_blank" rel="noopener" href="https://github.com/swaroopch/byte_of_python">A byte of python</a>(已看完)和python官网文档<a target="_blank" rel="noopener" href="https://docs.python.org/3/">Python 3.4.3 documentation</a>(其中的Tutorial已看完)。  </p>
<span id="more"></span>

<h2 id="To-Do"><a href="#To-Do" class="headerlink" title="To-Do:"></a>To-Do:</h2><p><del>1.配置好Hexo及VIM在windows下的环境。</del><br><del>2.在windows下编辑完本文其他内容。</del><br><del>3.回顾markdown语法，排版本文。</del><br><del>4.完成python官网Tutorial</del><br>5.使用python实现一个采集系统<br>6.使用pyton实现一个图像处理功能</p>
<h2 id="一、python的基本知识"><a href="#一、python的基本知识" class="headerlink" title="一、python的基本知识"></a>一、python的基本知识</h2><p>1.helloworld字符串的输出格式为<code>print(&#39;Hello world!&#39;)</code></p>
<p>2.python可以以多数模式运行.eg:<code>python -c command [arg]</code> #以命令行模式运行等，如果手动指定其运行模式则<code>sys.argv[0]</code>中存储的将是相应的参数<em>-c</em>,<em>-m</em>等否则是<em>sourcename</em>，即<code>sys.argv[0]</code>存储python命令后面的第一个参数。</p>
<p>3.python默认的源码文件为UTF-8格式，可以通过将语句<code># -*- coding: encoding -*-</code>放在源码第一行或者第二行来手动指定源文件格式。或者直接写成<code># encoding=utf-8</code></p>
<p>4.python注释以#开头，物理行结束，可以放在整行，空格或者代码后。</p>
<p>5.python的变量必须先赋值再使用，赋值相当于同时定义了变量，支持并列赋值和表达式中赋值。eg: <code>a,b = 1,2</code>  </p>
<p>6.交互模式下最后一次被打印的表达式存储在变量”_”中，这个变量对用户是只读的，但可以创建同名变量覆盖它。  </p>
<p>7.python内建支持<code>int,float,decimal,fraction,complex number</code>，使用”J”或“j”指定虚数位。</p>
<p>8.单引号与双引号的功能一样，类似于C里面的<code>printf()</code>中的双引号，三引号可以打印多行字符,也就是可以在程序中字符串的地方直接输入回车。反斜杠表示转义字符与C中一样，行尾的反斜杠”&quot;表示下一行是上一行的继续。在字符串引号前加R/r表示自然语言，也就是说里面的所有字符就只是单纯的字符，无法使用格式化输出，可以用于正则表达式。单引号内的双引号和双引号内的单引号不需要转义。</p>
<p>9.format为格式化输出，即使用参变量的值代替格式符{n}中的内容，<code>format()</code>可以有多个参数，例如：</p>
<p><code>&#39;&#123;0:.3&#125;&#39;.format(1/3)</code>输出为1/3保留3位小数<code>0.333</code>  </p>
<p><code>&#39;&#123;0:*^10&#125;&#39;.format(&#39;blueyi&#39;)</code> 以”*“在两边填充占用11位的”blueyi” 输出为 <code>**blueyi***</code>  </p>
<p><code>&#39;&#123;name&#125; &#123;age&#125;&#39;.format(name = &quot;blueyi&quot;,age = 3+2)</code> 输出为 <code>blueyi5</code> “{}”中的数字或者说内容是可选的  </p>
<p>print()函数打印时会自动在字符串结尾加上”\n”，可以手动指定结尾内容，如<code>print(&quot;he&quot;, end = &quot;&quot;)</code>不会换行，<code>name = &quot;blueyi&quot;;print(&quot;I&#39;m&quot;,name);</code>会打印<code>I&#39;m blueyi</code>  </p>
<p><code>input()</code>获取输入，eg: <code>age = int(input(&quot;Enter your age:&quot;))</code></p>
<p>10.操作符和表达式<br>大部分操作符与C语言一样，数学运算时<code>a ^ b</code>表示异或，即有且仅有一个真时为真。<code>a ** b</code>表示a的b次方，<code>a // b</code>表示取a对b取整，<code>a &lt;&lt; b</code>和<code>a &gt;&gt; b</code>表示a对应的二进制左移或者右移b位,C语言里面的位运算也能用，<code>～a</code>表示对a取反，<code>～a == -(a + 1)</code>，and、or、not对应逻辑中的与或非<br>可以使用<code>a += b</code>，不过没有“a++”类型的操作符。</p>
<p>11.可以使用分号;让两个逻辑行放在一个物理行里面，例如:<code>i = 1;print(i);</code></p>
<p>12.字符串是序列的一种，所有序列都可以通过“+”操作符连接，“*”操作符重复，都支持索引、切片以及使用len返回长度等。两个或者多个字符串紧挨在一起会被自动连接。eg: <code>&#39;max&#39; + &#39;wi&#39; == &#39;maxwi&#39; == &#39;max&#39;&#39;wi&#39;</code>  </p>
<p>13.字符串可以通过下标索引，索引可以为负数，但不能越界，str[-1]为最后一个最符，<code>str[-0] == str[0]</code>。  </p>
<p>14.字符串支持所有序列都支持的切片操作，切片操作<code>str[n1:n2]</code>返回n1到n2之间的字符串，含头不含尾。切片越界不会报错，会返回到字符串结尾。如果n1已经越界则返回空字符串。<code>s[:i] + s[i:] == s</code>  </p>
<p>15.字符串是不可变的，也就是不能对单一某一位上的字符进行修改。eg:<code>str[0] = &#39;a&#39;</code>会返回<code>TypeError</code>  </p>
<p>16.python中所有非0值为true，非空序列为true，空序列为false。</p>
<p>17.一般以双下划线开头和结尾的变量都是python内建或者程序中自己定义的具有特殊意义的变量。</p>
<h2 id="二、控制流"><a href="#二、控制流" class="headerlink" title="二、控制流"></a>二、控制流</h2><p>1、if-elif-else记得加:，eg：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> <span class="literal">True</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;Yes,it&#x27;s true&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>2、while语句与C类似，可选else，else语句将在循环结束后执行一次</p>
<p>3、<code>for...in...</code>语句in后面可以跟任何序列，也有一个与while类似的可选else。for语句和list()函数相当于一个遍历器。list()可以从可遍历序列创建一个列表。eg:<code>list(rang(5)) =&gt; [0,1,2,3,4]</code>   </p>
<p>3.1 for循环可用于遍历任何序列中的元素，遍历时若在循环内修改序列，则for循环的条件序列也会立即改变。所以for循环不会默认以副本形式的序列作为条件，最好以序列的拷贝进行遍历。eg:<code>for w in words[:];</code>该切片返回的是列表的拷贝。 </p>
<p>3.2 遍历数字序列时，可以使用内建的<code>range()</code>函数。eg:<code>for i in range(1, 5): pass;</code></p>
<p>3.3 <code>range(n)</code>为从0到n遍历数字，含头不含尾。<code>range(start, end, step)</code>表示以步长step从start遍历到end，step可以为负数。索引序列时可以混合使用<code>range()</code>和<code>len()</code>。eg:  </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="string">&#x27;I&#x27;</span>, <span class="string">&#x27;am&#x27;</span>, <span class="string">&#x27;blueyi&#x27;</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(a)):</span><br><span class="line">    <span class="built_in">print</span>(i, a[i])</span><br></pre></td></tr></table></figure>

<p>也可以使用枚举实现上述例子。eg:<code>list(enumerate(a));</code>  </p>
<p>3.4 <code>range()</code>为了节省空间，只在遍历时才返回连续的元素。实际上不会在内存中生成一个元素列表，所以<code>print(range(10)) =&gt;range(0,10)</code>   </p>
<p>3.5 <code>enumerate(iterable, start = 0)</code>表示默认从0开始遍历可遍历的序列对象。</p>
<p>4、continue和break在循环中与C中用法类似，分别表示继续下一次循环和跳出最近的for或while循环，pass表示空语句。</p>
<p>5、语句块以关键字加冒号再配合缩进组成，包括if,while,for,def</p>
<p>6、关键字in可用于测试序列中是否包含一个确定的值。eg:  </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> <span class="number">5</span> <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>):</span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<h2 id="三、函数"><a href="#三、函数" class="headerlink" title="三、函数"></a>三、函数</h2><ol>
<li><p>使用def定义函数,函数中的变量有全局，局部和非局部三种作用域。</p>
</li>
<li><p>函数中的所有变量都存储在一个局部列表中，引用变量时首先会查找局部列表，然后查找外部函数的局部列表，再然后是全局列表，最后是内建名称。</p>
</li>
<li><p>在函数体内部可以使用global关键字修饰全局变量，以便能在函数体内修改函数体外的变量。在函数体内定义的函数体中，可以使用关键字nonlocal修饰局部变量，使其成为非局部变量，以便可以在嵌套的内部函数中修改。一个关于作用域的例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">scope_test</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">do_local</span>():</span><br><span class="line">        spam = <span class="string">&quot;local spam&quot;</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">do_nonlocal</span>():</span><br><span class="line">        <span class="keyword">nonlocal</span> spam</span><br><span class="line">        spam = <span class="string">&quot;nonlocal spam&quot;</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">do_global</span>():</span><br><span class="line">        <span class="keyword">global</span> spam</span><br><span class="line">        spam = <span class="string">&quot;global spam&quot;</span></span><br><span class="line">    spam = <span class="string">&quot;test spam&quot;</span></span><br><span class="line">    do_local()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;After local assignment:&quot;</span>, spam)</span><br><span class="line">    do_nonlocal()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;After nonlocal assignment:&quot;</span>, spam)</span><br><span class="line">    do_global()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;After global assignment:&quot;</span>, spam)</span><br><span class="line"></span><br><span class="line">scope_test()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;In global scope:&quot;</span>, spam)</span><br></pre></td></tr></table></figure>
</li>
<li><p>定义形参时可以给形参赋值，为形参指定一个默认参数，只有参数表末尾的参数可以有默认值。当然也可以是这样<code>def func(a=5):</code></p>
</li>
<li><p><code>print(string * n)</code>表示打印n次string，其中n为整数，string为字符串</p>
</li>
</ol>
<p>6.为函数形参赋值时，实参按顺序赋给形参，也可以通过赋值语句而不考虑顺序，eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">func</span>(<span class="params">a, b=<span class="number">5</span>, c=<span class="number">6</span></span>):</span><br><span class="line">    <span class="keyword">pass</span>  <span class="comment"># 表示空语句</span></span><br></pre></td></tr></table></figure>
<p><code>func(1, 2, 3)</code>则a=1, b=2, c=3</p>
<p><code>func(3, c=2)</code>则a=3, b=5, c=2</p>
<p><code>func(c=3, a=2)</code>则a=2, b=5, c=3</p>
<p>注意：未指定默认值的参数必须赋值</p>
<p>6.形参所赋的默认值只会被计算一次，当拥有默认值的形参默认值是个可变列表时，要特别注意。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">func</span>(<span class="params">a, <span class="built_in">list</span>=[]</span>):</span><br><span class="line">\<span class="comment">#调用时只会被调用一次，每次调用都会将a添加到list形参</span></span><br><span class="line">    <span class="built_in">list</span>.append(a)</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">list</span></span><br></pre></td></tr></table></figure>
<p><code>l1 = func(1)</code> =&gt; l1 = [1]</p>
<p><code>l2 = func(2)</code> =&gt; l2 = [1,2]</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">func2</span>(<span class="params">a, <span class="built_in">list</span>=<span class="literal">None</span></span>):</span><br><span class="line">\<span class="comment">#调用时会首先检测是否list为None,如果是则将其清空</span></span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">list</span> <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        <span class="built_in">list</span> = []</span><br><span class="line">    <span class="built_in">list</span>.append(a)</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">list</span></span><br></pre></td></tr></table></figure>
<p><code>l3 = func2(1)</code> =&gt; l3 = [1]<br><code>l4 = func2(2)</code> =&gt; l4 = [2]</p>
<p>7.可以使用列表和字典来定义一个能获取任意个数参数的函数。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">func</span>(<span class="params">a=<span class="number">5</span>, *numbers, **keywords</span>):</span><br><span class="line">    total = a</span><br><span class="line">    <span class="keyword">for</span> number <span class="keyword">in</span> numbers:</span><br><span class="line">        total += number</span><br><span class="line">    <span class="keyword">for</span> key <span class="keyword">in</span> keywords:</span><br><span class="line">        total += keywords[key]</span><br><span class="line">    <span class="keyword">return</span> total</span><br><span class="line">func(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, a=<span class="number">4</span>, b=<span class="number">5</span>, c=<span class="number">6</span>)</span><br></pre></td></tr></table></figure>
<p>8.可以在带*的参数后面声明keyword-only参数.eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">func</span>(<span class="params">a=<span class="number">5</span>, *b, c</span>):</span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>调用func时c必须赋值，eg:<code>func(1, 2, 3, 4, c=8)</code></p>
<p>9.return返回函数值，无需指定函数的返回类型，没有return的函数默认返回None</p>
<p>10.Docstring文档字符串位于函数的第一个逻辑行，放在6个双引号”之间。可以使用<code>__doc__</code>(双下划线)引用eg:<code>print(func.__doc__)</code>  </p>
<p>11.lambda关键字可用于创建匿名函数，形式为<code>lambda parameters : expression</code>。也可以利用它创建返回函数的嵌套函数。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">make_func</span>(<span class="params">n</span>):</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">lambda</span> x : x+n</span><br><span class="line">f = make_func(<span class="number">42</span>)</span><br></pre></td></tr></table></figure>
<p><code>f(0)</code> =&gt; 42<br><code>f(1)</code> =&gt; 43</p>
<p>12.程序的元数据以字典形式存储在<code>__annotations__</code>变量中。可通过<code>func.__annotations__</code>读取。  </p>
<h2 id="四-数据结构"><a href="#四-数据结构" class="headerlink" title="四.数据结构"></a>四.数据结构</h2><p>列表，元组，字典，集合都属于结构化数据，有可变和不可变之分。<br>1.1列表：可变的序列，类方法操作后直接修改而不返回。可使用<code>for element in list:</code>遍历，使用[]定义。eg:<code>list = [&#39;I&#39;,&#39;am&#39;,&#39;blueyi&#39;]</code>,可以通过<code>list[n]</code>来访问第n个元素，<code>list.append(&#39;rice&#39;)</code>在列表尾添加一个元素，通过<code>del list[n]</code>删除第n个无素，<code>list.sort()</code>排序，<code>len(list)</code>查看其长度。</p>
<p>1.2 列表支持层叠.eg: <code>a = str1;b = str2;c = [a,b];</code></p>
<p>1.3 常的list类方法。</p>
<p><code>list.append(x)</code> 列表尾添加一个元素。&lt;=&gt; <code>a[len(a):] = [x]</code></p>
<p><code>list.extend(L)</code> 将列表L添加到list &lt;=&gt; <code>a[len(a):] = L</code></p>
<p><code>list.insert(i, x)</code> 在i位置前插入元素x。<code>a.insert(len(a), x)</code>  &lt;=&gt; <code>a.append(x)</code></p>
<p><code>list.remove(x)</code> 移除值为x的元素</p>
<p><code>list.pop([i])</code> 移除并返回位置i处的元素。[]表示可选项。<code>list.pop()</code>为移除最后一个元素</p>
<p><code>list.clear()</code> 删除list中所有元素 &lt;=&gt; <code>del a[:]</code></p>
<p><code>list.index(x)</code> 返回列表中第一个值为x的元素索引,若无x则报错。</p>
<p><code>list.count(x)</code> 返回列表中x出现的次数</p>
<p><code>list.sort()</code> 直接对当前列表进行排序</p>
<p><code>list.reverse()</code> 颠倒列表中的元素</p>
<p><code>list.copy()</code> 返回一个列表的浅拷贝 &lt;=&gt; <code>a[:]</code>。关于深浅拷贝<a target="_blank" rel="noopener" href="http://www.01happy.com/python-shallow-copy-and-deep-copy/">http://www.01happy.com/python-shallow-copy-and-deep-copy/</a></p>
<p>list的pop和append可以方便地将其当作堆栈来使用。利用<code>collections.deque()</code>可将列表当队列使用。</p>
<p>2.元组：不可变序列，可以将多样的对象集合到一起。使用<code>for element in tuple:</code>遍历，使用()定义，使用<code>tuple[n]</code>访问。eg:<code>tuple = (&#39;python&#39;,&#39;perl&#39;,&#39;ruby&#39;,&#39;php&#39;);tuple_plus = (&#39;C&#39;, &#39;C++&#39;, tuple);</code>则<code>tuple_plus[2][1][1] = +</code></p>
<p>2.1 声明含有0个元素的元组可以直接<code>tuple = ()</code>，仅含一个元素时后面必须要有个逗号，eg:<code>tuple = (&#39;blueyi&#39;,)</code></p>
<p>3.字典：就是键值对的集合，且没有顺序，其中键必须是惟一且不可变的，值是可变或者不可变的。可以使用<code>for key, value in dict.items():</code>遍历，声明方式为<code>dict = &#123;key1 : value1, key2 : value2&#125;</code> <code>del dict[key1]</code>删除键值对，<code>if key2 in dict</code>检验键值对是否存在。定义一个空字典：<code>dic = &#123;&#125;</code></p>
<p>4.列表，元组，字符串都属于序列，有着许多共同之处，他们者支持索引操作符”[ ]”，也支持切片操作。eg:<code>list[1:3]</code>返回<code>list[1],list[2]</code>，切片操作返回值包含首不包含尾，<code>list[:]</code>返回整个序列，<code>list[1:]</code>返回第一个到最后一个,<code>list[1:4:2]</code>以部长n返回，即<code>list[1],list[3],list[5]....</code>  </p>
<p>5.集合：没有顺序的，简单对象的聚类。声明方式为<code>sets = set([&#39;Pear&#39;, &#39;Apple&#39;, &#39;Orange&#39;])</code>，支持一些集合上的逻辑运算。</p>
<p>6.切片操作获得的是拷贝，而赋值操作获得的只是引用</p>
<p>7.记得使用help，查看更多相应类方法</p>
<p>8.一些常见的序列遍历方法</p>
<p>9.1 <code>items()</code>方法可以同时遍历字典中的key和value。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> k,v <span class="keyword">in</span> <span class="built_in">dict</span>.items():</span><br><span class="line">    <span class="built_in">print</span>(k, v)</span><br></pre></td></tr></table></figure>
<p>9.2 <code>enumerate()</code>函数可同时遍历序列中的index和value。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i,v <span class="keyword">in</span> <span class="built_in">enumerate</span>(<span class="built_in">list</span>):</span><br><span class="line">    <span class="built_in">print</span>(i,v)</span><br></pre></td></tr></table></figure>
<p>9.3 reversed()函数以相反的方向遍历序列。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">reversed</span>(<span class="built_in">range</span>(<span class="number">1</span>,<span class="number">10</span>,<span class="number">2</span>)):</span><br><span class="line">    <span class="built_in">print</span>(i, end=<span class="string">&#x27; &#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>=&gt;9 7 5 3 1</p>
<p>9.4 <code>zip()</code>函数可同时遍历多个序列。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">questions = [<span class="string">&#x27;name&#x27;</span>, <span class="string">&#x27;quest&#x27;</span>, <span class="string">&#x27;favorite color&#x27;</span>]</span><br><span class="line">answers = [<span class="string">&#x27;lancelot&#x27;</span>, <span class="string">&#x27;the holy grail&#x27;</span>, <span class="string">&#x27;blue&#x27;</span>]</span><br><span class="line"><span class="keyword">for</span> q, a <span class="keyword">in</span> <span class="built_in">zip</span>(questions, answers):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;What is your &#123;0&#125;?  It is &#123;1&#125;.&#x27;</span>.<span class="built_in">format</span>(q, a))</span><br></pre></td></tr></table></figure>
<p>What is your name?  It is lancelot.<br>What is your quest?  It is the holy grail.<br>What is your favorite color?  It is blue.  </p>
<p>9.5 <code>sorted()</code>函数返回一个已排序的序列而不改变原序列。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">sorted</span>(<span class="built_in">set</span>(<span class="built_in">list</span>)):</span><br><span class="line">    <span class="built_in">print</span>(i)  </span><br></pre></td></tr></table></figure>

<p>10.条件检查和比较</p>
<p>10.1 操作符”in”和”not in” 检查值是否出现在某个序列中</p>
<p>10.2 “is”和”is not” 检验两对象是否是同一对象，它们仅用于可变对象,如list.</p>
<p>10.3 所有的比较操作符优先级一样</p>
<p>10.4 比较可以级联。eg: <code>a &lt; b == c &lt;=&gt; a &lt; b and b == c</code></p>
<p>10.5 比较时可以混合使用布尔操作符and,or,not.它们的优先级比比较操作符低。其中not优先级最高，or优先级最低</p>
<p>10.6 布尔操作符中的and,or遵循短路原则</p>
<p>10.7 相同类型的序列对象之间可相互比较，遵照字典顺序。如果某一序列是另一序列的子序列，则较短的较小。序列元素为数字比较时，如果类型不一样，则近似比较。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>) &lt; (<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>)</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>] &lt; [<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>]</span><br><span class="line"><span class="string">&#x27;ABC&#x27;</span> &lt; <span class="string">&#x27;C&#x27;</span> &lt; <span class="string">&#x27;Pascal&#x27;</span> &lt; <span class="string">&#x27;Python&#x27;</span></span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>) &lt; (<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>)</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>) &lt; (<span class="number">1</span>, <span class="number">2</span>, -<span class="number">1</span>)</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>) == (<span class="number">1.0</span>, <span class="number">2.0</span>, <span class="number">3.0</span>)</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, (<span class="string">&#x27;aa&#x27;</span>, <span class="string">&#x27;ab&#x27;</span>)) &lt; (<span class="number">1</span>, <span class="number">2</span>, (<span class="string">&#x27;abc&#x27;</span>, <span class="string">&#x27;a&#x27;</span>), <span class="number">4</span>)</span><br></pre></td></tr></table></figure>

<h2 id="五-模块"><a href="#五-模块" class="headerlink" title="五.模块"></a>五.模块</h2><p>1.每一个’.py’文件的python都是一个模块，模块中可以包含函数，变量等</p>
<p>2.使用关键字import导入模块，eg:<code>import A</code>表示导入A到当前程序，引用时需要使用点操作符’.’来确定命名空间。<code>from A import B</code>表示导入A中的B到当前程序，<code>from A import *</code>导入A中的所有变量或者函数到当前程序(双下划线开始的变量除外)，这种导入方式引用时不需要”.”操作符，但容易与当前同名变量冲突，所以不推荐使用</p>
<p>3.模块的<code>__name__</code>可以控制主块的运行。这样模块就可以像脚本一样运行。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;run by itself&#x27;</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">     <span class="built_in">print</span>(<span class="string">&#x27;imported from another module&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>4.<code>sys.argv</code>中存储的是传递参数列表，<code>sys.argv[0]</code>是程序名，<code>sys.path</code>为sys的路径，<code>os.getcwd()</code>可以获取当前程序所在路径</p>
<p>5.<code>dir()</code>可用于显示模块的所有名称列表.eg:<code>dir(sys)</code>显示sys模块中的所有名称列表，<code>dir()</code>则显示当前模块中的名称列表。dir()不会列出内建程序名和变量名，要列出它们需要使用内建模块builtins。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> builtins</span><br><span class="line"><span class="built_in">dir</span>(builtins)</span><br></pre></td></tr></table></figure>

<p>6.<code>del a</code>语句用于删除变量/名称a</p>
<p>7.包可用于组织模块，是模块的文件夹，使用<code>__init__.py</code>文件来在模块文件夹根目录标明当前文件夹为包。包包含模块，模块包含函数和全局变量，函数中又包含变量 </p>
<ol start="8">
<li>一个模块在一次程序进程期间只会导入一次，修改模块后需要重启解释器，如果只是为了交互式的测试可使用imp.<code>reload()</code>重新载入模块。eg:<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> imp;</span><br><span class="line">imp.reload(modulename)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>9.编译模块为.pyc文件或者.pyo(通过-o参数，pyo为优化后的pyc文件，通常更小)。pyc文件通常为<code>__pycache__</code>目录下的<code>module.version.pyc</code>。这些文件有平台依赖性。</p>
<p>10..pyc或.pyo文件并不会使python程序运行更快，只是加快了载入速度。</p>
<p>11.python标准库就是python的标准模块,部分标准库依赖操作系统平台。eg:winreg模块仅在windows下有</p>
<ol start="12">
<li><code>sys.ps1</code>存储的是交互模式下的提示符’&gt;&gt;&gt;’，<code>sys.path.append(&#39;string&#39;)</code>可追加<code>PYTHONPATH</code>  </li>
</ol>
<p>13.使用包管理模块时可嵌套目录，使用点操作符引用。eg: <code>import item.subitem.subsubitem</code>最后一个元素可以是个模块或者包，但不能是类、函数或变量。</p>
<h2 id="六、类"><a href="#六、类" class="headerlink" title="六、类"></a>六、类</h2><p>1.类使用关键字class创建，eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">blueyi = Person()</span><br><span class="line"><span class="built_in">print</span>(blueyi)</span><br></pre></td></tr></table></figure>
<p>属于一个类或者对象的变量称为域，域又可称为属于实例的实例变量，和属于对象或者类本身的类变量。</p>
<p>2.类对象支持2种操作，一种是属性引用。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Myclass</span>:</span><br><span class="line">    i = <span class="number">1</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">f</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;Hi&#x27;</span></span><br><span class="line"></span><br><span class="line">Myclass.i    <span class="comment">#引用类变量</span></span><br><span class="line">Myclass.f()  <span class="comment">#引用类函数</span></span><br></pre></td></tr></table></figure>
<p>另一种是实例引用,即创建一个Myclass的实例。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">x = Myclass()</span><br><span class="line"></span><br><span class="line">x.i    <span class="comment">#引用实例变量</span></span><br><span class="line">x.f()  <span class="comment">#引用实例方法 &lt;=&gt; Myclass.f(x)</span></span><br></pre></td></tr></table></figure>

<p>3.类方法与普通函数的区别是类方法必须有第一个参数且指向对象本身，通常称为self.注意不是指定类，而是指定类创建的对象本身。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">sayHi</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Hi!&#x27;</span>)</span><br><span class="line">p = Person()</span><br><span class="line">p.sayHi()</span><br></pre></td></tr></table></figure>
<p>4.类可以通过<code>__init__()</code>方法初始化，<code>__init__</code>函数会在类对象创建时立即运行，相当于C++的构造函数。<code>__del__()</code>方法用于在对象被删除时运行，例如使用del语句删除对象。它们也必须要有self参数。</p>
<p>5.与类变量名字相同的实例变量会隐藏类变量。类变量在所有实例之间共享，可以被它们修改，而实例变量是由各个实例所私有。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Dog</span>:</span><br><span class="line">    kind = <span class="string">&#x27;Canine&#x27;</span>    <span class="comment">#类变量</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name</span>):</span><br><span class="line">        self.name = name    <span class="comment">#实例变量</span></span><br></pre></td></tr></table></figure>
<p>6.同名的数据属性会覆盖掉方法属性。</p>
<p>7.以双下划线开头的变量都是私有变量。如果某个变量想只在对象和类中使用，最好以单下划线开关。pep8规范</p>
<p>8.类继承是通过元组在定义子类时将父类作为元组元素来实现继承。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Company</span>:</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Dell</span>(<span class="title class_ inherited__">Company</span>):</span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p>9.python支持多重继承，继承的属性从第一个父类开始从左至右搜索到为止。</p>
<p>10.所有类都继承自object。</p>
<p>11.一些常用的特殊类方法</p>
<p><code>object.__init__(self,[...])</code> 新创建的对象返回之前调用，用于初始化对象</p>
<p><code>object.__del__(self)</code> 对象被销毁前调用</p>
<p><code>object.__str__(self)</code> 当使用print函数或者<code>str()</code>函数时调用</p>
<p><code>object.__lt__(self,other)</code> 当使用&lt;操作符时调用，对应的有<code>object.__eq__(self, other) object.__ne__(self, other) object.__gt__(self, other)object.__ge__(self, other)</code>  </p>
<p><code>object.__getitem__(self, key)</code> 使用索引操作符<code>x[index]</code>时调用</p>
<p><code>object.__len__(self)</code> 当内建的<code>len()</code>函数对序列对象使用时调用  </p>
<p>12.检查类的两个方法：</p>
<p><code>isinstance(obj, class)</code> 检查实例类型</p>
<p><code>issubclass(class1, class2)</code> 检查class是否继承自class2</p>
<h2 id="七、输入输出"><a href="#七、输入输出" class="headerlink" title="七、输入输出"></a>七、输入输出</h2><p>1.字符串的输入输出是通过<code>input(prompt)</code>和<code>print(string)</code>.eg: </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="built_in">input</span>(<span class="string">&#x27;Enter your string:&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(text)</span><br></pre></td></tr></table></figure>

<p>2.<code>repr()</code>和<code>str()</code>都会强制将任何值强制转换为一个字符串并返回，其中<code>repr()</code>返回一个解释器易于处理的形式，而<code>str()</code>会返回一个人易读的形式。</p>
<p>3.<code>str.rjust(width[ ,filechar])</code>右对齐并以fillchar填充，相应的有<code>ljust()</code>,<code>center()</code>。这些方法不会修改原str，只是返回一个新的str。<code>str.format()</code>可对字符串进行格式化转化。</p>
<p>4.对于文件的读写使用<code>open(filename, mode),close(),write(),read(),readline()</code>等方法，以UTF-8格式打开文件，打开方式可选且多数与C类似，默认为以文本方式读或者写，默认mode为<code>r</code>。<br><strong>默认的这些文件读写方法由os包提供，是较低级的文件读写接口，尽量使得io包提供的文件读写接口：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># encoding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> io</span><br><span class="line">f = io.<span class="built_in">open</span>(<span class="string">&quot;abc.txt&quot;</span>, <span class="string">&quot;wt&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>)</span><br><span class="line">f.write(<span class="string">u&quot;Imagine non-English language here&quot;</span>)</span><br><span class="line">f.close()</span><br><span class="line">text = io.<span class="built_in">open</span>(<span class="string">&quot;abc.txt&quot;</span>, encoding=<span class="string">&quot;utf-8&quot;</span>).read()</span><br><span class="line"><span class="built_in">print</span>(text)</span><br></pre></td></tr></table></figure>

<p>5.文件读写的文本模式下，默认读取时会自动转换换行符(<code>\n on unix,\r\n on windows</code>)为<code>\n</code>,写会进行相反的操作。</p>
<p>6.File的常用类方法(假定已经创建了名为f的file对象)：</p>
<p>6.1 <code>f.read([size])</code>读取size bytes大小的数据，返回一个字符串或字节对象，若省略size则返回整个文件内容，若文件过大则会出错，达到文件尾会返回空字符串。</p>
<p>6.2 <code>f.readline()</code>读取单独的一行，包含<code>\n</code>。返回空字符串时表示到达文件尾。可使用更高效的循环代替。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> f:</span><br><span class="line">    <span class="built_in">print</span>(line, end=<span class="string">&#x27;&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>6.3 <code>f.readlines()</code> 读取文件中的所有行到列表。也可使用list(f)</p>
<p>6.4 <code>f.write(string)</code> 将string写入文件并返回写入的字符数。若写入的内容不是字符串则需要手动转换。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">value = (<span class="string">&#x27;the answer&#x27;</span>, <span class="number">42</span>)</span><br><span class="line">s = <span class="built_in">str</span>(value)</span><br><span class="line">f.write(s)</span><br></pre></td></tr></table></figure>

<p>6.5 <code>f.tell()</code> 返回一个标示当前文件对象所指向文件位置的整数，二进制模式表示从文件头到当前位置的字节数。文本模式下为一个opaque number。</p>
<p>6.6 <code>f.seek(offset[, from_what])</code> 以frome_what为参考位置修改f的指向位置。from_what可取0、1、2分别表示文件开头、当前位置、文件结尾，默认为0。</p>
<p>6.7 <code>f.close()</code> 关闭文件并释放资源。</p>
<p>6.8 <code>f.closed()</code> 查看当前文件是否已被关闭。</p>
<p>7.建议使用<code>with...as...</code>语句读写文件  eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&#x27;temp.txt&#x27;</span>, <span class="string">&#x27;r&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> f:</span><br><span class="line">        <span class="built_in">print</span>(line, end=<span class="string">&#x27;_&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>with 获取open返回的对象，以f引用，在执行它后的语句块之前会先执行返回对象的<strong>enter</strong>方法。执行完语句块之后会执行返回对象的<strong>exit</strong>方法。无需手动关闭文件。   </p>
<p>8.<code>open()</code>方法默认以utf-8格式打开文件，也可以手动指定编码格式。eg: <code>f = open(&#39;temp.txt&#39;, &#39;wt&#39;, encoding=&#39;utf-8&#39;)</code>  </p>
<p>9.利用pickle模块的dump()和load()方法可以将对象存储到文件中然后在需要的时候读取,存取时要以二进制模式读写,且存储的文件仅能用于python中。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pickle</span><br><span class="line">listfile = <span class="string">&#x27;list.data&#x27;</span></span><br><span class="line"><span class="built_in">list</span> = [<span class="string">&#x27;China&#x27;</span>, <span class="string">&#x27;Japan&#x27;</span>, <span class="string">&#x27;America&#x27;</span>]</span><br><span class="line">f = <span class="built_in">open</span>(listfile, <span class="string">&#x27;wb&#x27;</span>)</span><br><span class="line">pickle.dump(<span class="built_in">list</span>, f)</span><br><span class="line">f.close()</span><br><span class="line"><span class="keyword">del</span> <span class="built_in">list</span></span><br><span class="line">f = <span class="built_in">open</span>(listfile, <span class="string">&#x27;rb&#x27;</span>)</span><br><span class="line"><span class="built_in">list</span> = pickle.load(f)</span><br><span class="line">f.close()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>)</span><br></pre></td></tr></table></figure>

<p>10.json模块与pickle相反，它可将结构化的数据存储到可交换的数据文件格式json中，使用<code>json.dump(x, f)</code>将x写入f，<code>x = json.load(f)</code>,将f内容读入到x。  </p>
<h2 id="八-异常"><a href="#八-异常" class="headerlink" title="八.异常"></a>八.异常</h2><p>1.通过<code>try...except...else</code>语句处理异常，功能语句放在try块中，错误处理语句放在except块中，没有任何异常则运行else中的语句，else语句可选。<br>如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    text = <span class="built_in">input</span>(<span class="string">&#x27;Enter something --&gt; &#x27;</span>)</span><br><span class="line"><span class="keyword">except</span> EOFError:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;Why did you do an EOF on me?&#x27;</span>)</span><br><span class="line"><span class="keyword">except</span> KeyboardInterrupt:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;You cancelled the operation.&#x27;</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;You entered &#123;&#125;&#x27;</span>.<span class="built_in">format</span>(text))</span><br></pre></td></tr></table></figure>

<p>2.except中可加入多个异常。eg:<code>except(RuntimeError, TypeError, NameError):</code>,最后一个异常名可以使用通配符。</p>
<p>3.自己可以创建继承至Error或者Exception类的异常，使用raise可以引发错误或者异常，用户定义的异常应该直接或者间接地继承自Exception。</p>
<p>4.使用<code>try...finally...</code>可以在无论异常发生与否的情况下都执行finally语句块中的内容</p>
<p>5.可选的finally语句在实际应用中可用于释放外部资源，如关闭文件或网络连接。</p>
<p>6.有些对象预定义了清理动作，如file，可通过<code>with...as...</code>语句体现。with语句处理完文件后，无论哪种情况下都会关闭文件。</p>
<h2 id="九-其他"><a href="#九-其他" class="headerlink" title="九.其他"></a>九.其他</h2><p>1.利用元组可以获得函数一次返回的两个值。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">getStudent</span>():</span><br><span class="line">    <span class="keyword">return</span> (<span class="string">&#x27;blueyi&#x27;</span>, <span class="number">23</span>)</span><br><span class="line">name, age = getstudent()</span><br></pre></td></tr></table></figure>
<p><code>a, *b = [1,2,3,4]</code> 则<code>a = 1,b = [2,3,4]</code></p>
<p>2.Python中的迭代器。<br>2.1迭代器遍布于python之中，最常见是for循环通过调用可迭代对象的<code>iter()</code>方法来进行循环迭代。其中<code>iter()</code>方法相当于一个对象容器，每次返回一个迭代器对象，迭代器对象中定义的<code>__next__()</code>方法用来在每次迭代时返回<code>iter()</code>中的下一个元素，当没有任何元素时，<code>__next__()</code>将引发<code>StopIteration</code>异常。可以使用内置函数<code>next()</code>来调用<code>__next__()</code>方法。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> element <span class="keyword">in</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]:</span><br><span class="line">    <span class="built_in">print</span>(element)</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&#x27;abc&#x27;</span></span><br><span class="line">it = <span class="built_in">iter</span>(s)</span><br><span class="line"><span class="built_in">next</span>(it)   <span class="comment">#输出a</span></span><br><span class="line"><span class="built_in">next</span>(it)   <span class="comment">#输出b</span></span><br><span class="line"><span class="meta">... </span>       <span class="comment">#直到迭代完成引发`StopIteration`异常。</span></span><br></pre></td></tr></table></figure>

<p>2.2 可通过在类中增加<code>__iter()__</code>方法返回对象本身给<code>__next__()</code>方法来为自己的类增加迭代功能。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Reverse</span>:</span><br><span class="line">    <span class="string">&quot;&quot;&quot;Iterator for looping over a sequence backwards.&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, data</span>):</span><br><span class="line">        self.data = data</span><br><span class="line">        self.index = <span class="built_in">len</span>(data)</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__iter__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__next__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> self.index == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">raise</span> StopIteration</span><br><span class="line">        self.index = self.index - <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> self.data[self.index]</span><br><span class="line"></span><br><span class="line">rev = Reverse(<span class="string">&#x27;blueyi&#x27;</span>)</span><br><span class="line"><span class="keyword">for</span> char <span class="keyword">in</span> rev:</span><br><span class="line">    <span class="built_in">print</span>(char, end=<span class="string">&#x27; &#x27;</span>)    <span class="comment">#输出为i y e u l b</span></span><br></pre></td></tr></table></figure>

<p>3.Python中的生成器。</p>
<p><code>yield</code>语句可以用于创建迭代器，能够实现通过<code>__iter__()</code>和<code>__next__()</code>实现的功能。每次 next() 被调用时, 生成器会从它上次离开的地方继续执行，它会记住所有的数据值和最后一次执行的语句。eg:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">reverse</span>(<span class="params">data</span>):</span><br><span class="line">    <span class="keyword">for</span> index <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(data)-<span class="number">1</span>, -<span class="number">1</span>, -<span class="number">1</span>):</span><br><span class="line">        <span class="keyword">yield</span> data[index]</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> char <span class="keyword">in</span> reverse(<span class="string">&#x27;blueyi&#x27;</span>):</span><br><span class="line">    <span class="built_in">print</span>(char, end=<span class="string">&#x27; &#x27;</span>)    <span class="comment">#输出为i y e u l b</span></span><br></pre></td></tr></table></figure>

<p>4.Generator表达式比列表实现的相同功能更省内存。</p>
<p><code>sum(i*i for i in range(10))</code>   #计算平方和，输出为285</p>
<h2 id="十-标准库"><a href="#十-标准库" class="headerlink" title="十.标准库"></a>十.标准库</h2><p>1.sys包含系统指定的函数功能</p>
<p>2.os用来和系统交互</p>
<p>3.plantform用来获得平台信息</p>
<p>4.logging用来记录信息</p>
<p>5.urllib网络相关  </p>
<h2 id="拾遗"><a href="#拾遗" class="headerlink" title="拾遗"></a>拾遗</h2><h3 id="函数装饰器：-classmethod-staticmethod-property"><a href="#函数装饰器：-classmethod-staticmethod-property" class="headerlink" title="函数装饰器：@classmethod, @staticmethod, @property"></a>函数装饰器：@classmethod, @staticmethod, @property</h3><p>函数装饰器通常用于放在类方法前面修饰类内部定义的函数。<br>类的成员函数可以通过上述提到的3个装饰器来修饰，区别主要如下：</p>
<ul>
<li>普通成员函数，即不使用任何装饰器来修饰的成员函数即为方法，它属于类的实例化对象，且只能通过实例化之后的类对象调用，而不能通过类本身来直接调用（当然可以通过显示传递实例的方式调用），即普通成员函数与类的实例绑定。普通成员函数的第一个参数默认为当前类的实例，即通常用的self。</li>
<li>@classmethod修饰的方法属于类方法，类方法属于类本身，且被所有类的实例共有，该方法的第一个参数默认为类本身，而不是类的实例，通常使用cls来表示第一个形参。该方法可以通过类名来直接调用，或者通过类的实例来调用，即该方法与类本身绑定。它可以访问数据成员及成员函数</li>
<li>@staticmethod修饰的方法为静态方法，类似C++中的静态方法，该方法不与类及类对象绑定，它的第一个参数也不要求必须是谁，可以没有第一个参数（其他类方法第一个参数都默认为类本身或实例本身）。该方法即可以直接通过类来调用，也可以通过类的实例调用。它不能访问实例的属性（数据成员或成员函数）</li>
<li>@property装饰器可以将方法设置为对象的属性，当一个函数被@property修饰时，python默认会为该类增加一个相应函数的getter, setter和deleter属性，默认的@property修饰的方法就是getter方法，如下面的官方示例：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">C</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self._x = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">x</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;I&#x27;m the &#x27;x&#x27; property.&quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self._x</span><br><span class="line"></span><br><span class="line"><span class="meta">    @x.setter</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">x</span>(<span class="params">self, value</span>):</span><br><span class="line">        self._x = value</span><br><span class="line"></span><br><span class="line"><span class="meta">    @x.deleter</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">x</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">del</span> self._x</span><br><span class="line"></span><br><span class="line"><span class="comment">#使用</span></span><br><span class="line">c = C()</span><br><span class="line">c.x = <span class="number">5</span></span><br><span class="line"><span class="built_in">print</span>(c.x)</span><br></pre></td></tr></table></figure>

<p>一个针对性举例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#! /usr/bin/env python</span></span><br><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">C</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;普通函数&quot;&quot;&quot;</span></span><br><span class="line">        self._x = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">com_fun</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;普通函数&quot;&quot;&quot;</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;I am common function&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">class_method</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;类方法，可以通过类名直接调用&quot;&quot;&quot;</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;I am class method: &#x27;</span> + <span class="built_in">str</span>(self.x))</span><br><span class="line"></span><br><span class="line"><span class="meta">    @staticmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">st_method</span>():</span><br><span class="line">        <span class="string">&quot;&quot;&quot;静态方法，可以通过类名或实例直接调用，可以没有参数&quot;&quot;&quot;</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;I am static method&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">x</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;I&#x27;m the &#x27;x&#x27; property.&quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self._x</span><br><span class="line"></span><br><span class="line"><span class="meta">    @x.setter</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">x</span>(<span class="params">self, value</span>):</span><br><span class="line">        self._x = value</span><br><span class="line"></span><br><span class="line"><span class="meta">    @x.deleter</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">x</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">del</span> self._x</span><br><span class="line"></span><br><span class="line">c = C()</span><br><span class="line">c.com_fun()  <span class="comment">#通过实例调用普通函数，实际上该函数有第一个参数self，self即实例本身</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;c.com_fun: &#x27;</span> + <span class="built_in">str</span>(c.com_fun))  <span class="comment">#查看函数绑定情况</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># C.com_fun()  #通过类用普通函数将出错</span></span><br><span class="line">C.com_fun(c)  <span class="comment">#可以通过显式传递实例名的方式通过类名调用普通成员函数</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;C.com_fun(c): &#x27;</span> + <span class="built_in">str</span>(C.com_fun))  <span class="comment">#查看函数绑定情况</span></span><br><span class="line"></span><br><span class="line">c.class_method() <span class="comment">#通过实例调用类方法，实际上该方法的第一个参数cls为类本身</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;c.class_method: &#x27;</span> + <span class="built_in">str</span>(c.class_method))</span><br><span class="line"></span><br><span class="line">C.class_method() <span class="comment">#通过类调用类方法</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;C.class_method: &#x27;</span>+ <span class="built_in">str</span>(C.class_method))</span><br><span class="line"></span><br><span class="line">c.st_method()  <span class="comment">#通过实例调用静态方法，该函数参数列表为空，不存在第一个参数</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;c.st_method: &#x27;</span> + <span class="built_in">str</span>(c.st_method))</span><br><span class="line">C.st_method()  <span class="comment">#通过实例调用静态方法</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;C.st_method: &#x27;</span> + <span class="built_in">str</span>(C.st_method))</span><br><span class="line"></span><br><span class="line">c.x = <span class="number">5</span> <span class="comment">#通过setter属性为实例成员变量赋值</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;c.x: &#x27;</span> + <span class="built_in">str</span>(c.x))  <span class="comment">#通过getter属性获取实例变量的值</span></span><br><span class="line"><span class="keyword">del</span> c.x  <span class="comment">#通过deleter属性删除实例变量</span></span><br><span class="line"><span class="comment"># print(c.x)  #加上这句将运行出错，因为已经通过属性删除了c._x</span></span><br></pre></td></tr></table></figure>

<p>运行结果：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">I am common function</span><br><span class="line">c.com_fun: &lt;bound method C.com_fun of &lt;__main__.C object at 0x0000000002A64E10&gt;&gt;</span><br><span class="line">I am common function</span><br><span class="line">C.com_fun(c): &lt;unbound method C.com_fun&gt;</span><br><span class="line">I am class method: &lt;property object at 0x0000000002A790E8&gt;</span><br><span class="line">c.class_method: &lt;bound method type.class_method of &lt;class &#x27;__main__.C&#x27;&gt;&gt;</span><br><span class="line">I am class method: &lt;property object at 0x0000000002A790E8&gt;</span><br><span class="line">C.class_method: &lt;bound method type.class_method of &lt;class &#x27;__main__.C&#x27;&gt;&gt;</span><br><span class="line">I am static method</span><br><span class="line">c.st_method: &lt;function st_method at 0x0000000002A77748&gt;</span><br><span class="line">I am static method</span><br><span class="line">C.st_method: &lt;function st_method at 0x0000000002A77748&gt;</span><br><span class="line">c.x: 5</span><br></pre></td></tr></table></figure>
<p>从结果中可以看到com_method绑定到了C的对象，class_method与类本身绑定，st_method没有绑定</p>
<h3 id="requirements-txt"><a href="#requirements-txt" class="headerlink" title="requirements.txt"></a>requirements.txt</h3><p><code>pip freeze &gt; requirements.txt</code> 生成依赖<br><code>pip install -r requirements.txt</code> 安装依赖</p>
<p>参考：<br><a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python">http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python</a><br><a target="_blank" rel="noopener" href="http://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner">http://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner</a><br><a target="_blank" rel="noopener" href="http://blog.csdn.net/slvher/article/details/42497781">http://blog.csdn.net/slvher/article/details/42497781</a><br><a target="_blank" rel="noopener" href="https://docs.python.org/2/library/functions.html#property">https://docs.python.org/2/library/functions.html#property</a></p>

    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Notes/" rel="tag"># Notes</a>
              <a href="/tags/Python/" rel="tag"># Python</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2015/04/09/git-study-notes/" rel="prev" title="Git学习笔记">
      <i class="fa fa-chevron-left"></i> Git学习笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2015/06/11/CUDA-study-notes/" rel="next" title="CUDA学习笔记">
      CUDA学习笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#To-Do"><span class="nav-number">1.</span> <span class="nav-text">To-Do:</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E3%80%81python%E7%9A%84%E5%9F%BA%E6%9C%AC%E7%9F%A5%E8%AF%86"><span class="nav-number">2.</span> <span class="nav-text">一、python的基本知识</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%8E%A7%E5%88%B6%E6%B5%81"><span class="nav-number">3.</span> <span class="nav-text">二、控制流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E5%87%BD%E6%95%B0"><span class="nav-number">4.</span> <span class="nav-text">三、函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-number">5.</span> <span class="nav-text">四.数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94-%E6%A8%A1%E5%9D%97"><span class="nav-number">6.</span> <span class="nav-text">五.模块</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD%E3%80%81%E7%B1%BB"><span class="nav-number">7.</span> <span class="nav-text">六、类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83%E3%80%81%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA"><span class="nav-number">8.</span> <span class="nav-text">七、输入输出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AB-%E5%BC%82%E5%B8%B8"><span class="nav-number">9.</span> <span class="nav-text">八.异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B9%9D-%E5%85%B6%E4%BB%96"><span class="nav-number">10.</span> <span class="nav-text">九.其他</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%81-%E6%A0%87%E5%87%86%E5%BA%93"><span class="nav-number">11.</span> <span class="nav-text">十.标准库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8B%BE%E9%81%97"><span class="nav-number">12.</span> <span class="nav-text">拾遗</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%9A-classmethod-staticmethod-property"><span class="nav-number">12.1.</span> <span class="nav-text">函数装饰器：@classmethod, @staticmethod, @property</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#requirements-txt"><span class="nav-number">12.2.</span> <span class="nav-text">requirements.txt</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="blueyi"
      src="/images/default_avatar.jpg">
  <p class="site-author-name" itemprop="name">blueyi</p>
  <div class="site-description" itemprop="description">心怀善意，虛怀若谷！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">104</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">68</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/blueyi" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;blueyi" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://maxwi.com/" title="http:&#x2F;&#x2F;maxwi.com" rel="noopener" target="_blank">Maxwi</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2014 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">blueyi</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="Symbols count total">750k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">11:22</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '0f8243eb2c8b2207980f',
      clientSecret: 'd159633a33519d3b7a48b0ca729032f7d1f38a41',
      repo        : 'notes',
      owner       : 'blueyi',
      admin       : ['blueyi'],
      id          : '45a0fbe3efc7840454762f3f8fd5b839',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

    </div>
</body>
</html>
